package com.company;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 把文本文件通过处理后，转换格式，再输出
 * @date : 2023-06-15 下午7:35
 */

public class P058_TransferText {


    public static void main(String[] args) {
        String s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>》，。【】";
        char[] chars = s.toCharArray();
        Set<Character> set = new HashSet<>();
        for (char c : chars) {
            set.add(c);
        }
        String filename = "需要自动换行的文件";
        String encoding = "UTF-8";
        int num = 40;

        List<String> stringList = readFile(filename, encoding);
        List<String> list = new ArrayList<>();
        for (String string : stringList) {
            num = 40;
            if (string.length() < num) {
                list.add(string);
                continue;
            }
            while (string.length() > num) {
                num = 40;
                while (string.length() > num && set.contains(string.charAt(num))) {
                    num++;
                }
                list.add(string.substring(0, num));
                string = string.substring(num);
            }
            list.add(string);
        }
        createTxt(list, filename, encoding);
    }


    private static List<String> readFile(String filename, String encoding) {
        List<String> ans = new ArrayList<>();
        try (BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream(filename), encoding))) {
            String line;
            while ((line = buf.readLine()) != null) {
                ans.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ans;
    }

    private static void createTxt(List<String> list, String filename, String encoding) {
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(filename), encoding))) {
            for (String s : list) {
                bw.write(s);
                bw.newLine();
                bw.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
